﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using DatabaseCore.Dao;
using System.Threading;

namespace Export.App.Service
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public SQLNotifier Notifier { get; set; }
        private Timer timer;
        private DispatcherTimer dispatcherTimer;

        public MainWindow()
        {
            InitializeComponent();
            timer = new Timer(OnTimer, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
            dispatcherTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 1) };
            dispatcherTimer.Tick += OnDispatcherTimer;

            Notifier = new SQLNotifier();
            Notifier.NewMessage += new EventHandler<SqlNotificationEventArgs>(notifier_NewMessage);
            DataTable dt = Notifier.RegisterDependency(true); //register only when run app
            dispatcherTimer.Start();
        }

        private void StartTimer(object sender, RoutedEventArgs e)
        {
            timer.Change(TimeSpan.Zero, new TimeSpan(0, 0, 1));

            // Disable the start buttons and enable the reset button.
        }

        private void OnTimer(object state)
        {
            Dispatcher.Invoke(() => ShowTime());
        }

        private void ShowTime()
        {
            Clock.Content = DateTime.Now.ToString("hh:mm:ss");
        }

        private void OnDispatcherTimer(object sender, EventArgs e)
        {
            ShowTime();
        }

        private void notifier_NewMessage(object sender, SqlNotificationEventArgs e)
        {
            DataTable dt = Notifier.RegisterDependency();
            if (dt != null)
            {
                SystemCore.Helper.ExceptionHelper.Log("Get data " + dt.Rows.Count + " rows");
                InitialData(dt);
            }
        }

        private void InitialData(DataTable dt)
        {
            this.Dispatcher.BeginInvoke((Action)delegate()
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    string materialNoOut = null;
                    string plantOut = null;
                    decimal qtyReceivedOut = 0;
                    decimal palletDetailIdOut = 0;

                    //hardcode to top 5 due to get top on sql notifier is not working
                    for (int i = 0;  i < dt.Rows.Count && i < 5; i++) //dt.Rows.Count; i++)
                    {
                        DataRow q = dt.Rows[i];
                        /* Call CalProductQueue */
                        var palletDetailID = Convert.ToDecimal(q["PalletDetailID"]);
                        var materialNo = q["ProductCode"].ToString();
                        var plant = q["PlantDestination"] != null && !string.IsNullOrEmpty(q["PlantDestination"].ToString()) ? q["PlantDestination"].ToString() : q["PlantCode"].ToString();
                        //ใช้ baseunitQty แทน productQty
                        var qty = Convert.ToDecimal(q["BaseUnitQty"]);


                        var result = Notifier.CallSp_CalProductQueue(palletDetailID, materialNo, plant, qty, out materialNoOut, out plantOut, out qtyReceivedOut, out palletDetailIdOut);

                        SystemCore.Helper.ExceptionHelper.Log(result);
                    }
                    //foreach (DataRow q in dt.Rows )
                    //{
                        

                     //   i++;
                        //Cancel - call in CallSp_CalProductQueue the same connection
                        //CallWebService(materialNoOut, plantOut, qtyReceivedOut, palletDetailIdOut)

                        //Test call procedure too long
                        //Notifier.CallSp_WaitForDelay();
                    //}
                }
            });
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

        private void btnCallSp_Click(object sender, RoutedEventArgs e)
        {
            string palletID;
            string errorCode;
            string errorMessage;

            Notifier.CallSp_PalletCreatePalletID(out palletID, out errorCode, out errorMessage);
            Label1.Content = "Pallet ID = " + palletID;
            Label2.Content = "Error Code = " + errorCode;
            Label3.Content = "Error Message = " + errorMessage;
        }

        private void btnUpdatePlant_Click(object sender, RoutedEventArgs e)
        {
            Notifier.UpdatePlant();
            //Notifier.TestConnection();
        }
    }
}
